package com.kc.common.utils;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.aliyun.oss.OSSClient;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @ClassName SharePosterUtils
 * @Description TODO
 * @Author wangdongliang
 * @Date 2021/3/24 10:42
 */
@Slf4j
@Component
public class SharePosterUtils {
    @Value("${share.distribution.url}")
    private  String url;
    @Value("${share.distribution.imgpath}")
    private  String imgpath;
    @Resource
    private OSSUtils ossUtils;

    /**
     * 生成二维码
     * @param userId
     * @return
     */
    public String qrcode(Integer userId){
        //logo 图片
        String logoImage = imgpath + "/logo.png";
        String createImage =  imgpath + "/" + userId + ".png";
        //执行生成二维码
        try {
            QrConfig config = new QrConfig(150, 150);
            config.setMargin(0);
            config.setImg(logoImage);
            config.setErrorCorrection(ErrorCorrectionLevel.H);
            QrCodeUtil.generate(
                    url + "?pid=" + userId, //二维码内容
                    config,
                    FileUtil.file(createImage)//写出到的文件
            );
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return composeImage(createImage, userId);
        }catch (Exception e){
            return null;
        }
    }
    //合成图片
    public String composeImage(String qrcodePath,Integer userId){
        String outImage = imgpath + "/poster_" + userId + ".png";
        try {
            String backgroundImage = imgpath + "/backgroundImage.png";
            ImgUtil.pressImage(
                    FileUtil.file(backgroundImage),
                    FileUtil.file(outImage),
                    ImgUtil.read(FileUtil.file(qrcodePath)), //水印图片
                    180, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                    260, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                    1f
            );
            //上传oss
            OSSClient client = ossUtils.getOSSClient();
            String ossPath = ossUtils.uploadObject2OSS(client,new File(outImage));
            return ossPath;
        }catch (Exception e){
            return null;
        }finally {
            File file = new File(qrcodePath);
            file.delete();
            new File(outImage).delete();
        }

    }
}
